package cn.ztydata.teachingsystem.heaven.service;

import cn.ztydata.teachingsystem.common.Page;
import cn.ztydata.teachingsystem.exception.ServiceException;
import cn.ztydata.teachingsystem.heaven.common.WebContext;
import cn.ztydata.teachingsystem.heaven.cons.QuestionCons;
import cn.ztydata.teachingsystem.heaven.cons.Roles;
import cn.ztydata.teachingsystem.heaven.dao.AnswerDao;
import cn.ztydata.teachingsystem.heaven.dao.QuestionDao;
import cn.ztydata.teachingsystem.heaven.dao.redis.QuestionPvAnCountDao;
import cn.ztydata.teachingsystem.heaven.entity.Answer;
import cn.ztydata.teachingsystem.heaven.entity.Question;
import cn.ztydata.teachingsystem.heaven.entity.Student;
import cn.ztydata.teachingsystem.heaven.entity.Teacher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 问题答案业务
 *
 * @author lyj
 * @since 2015-3-20
 */
@Service
public class AnswerService extends BaseService {
    @Autowired
    private AnswerDao answerDao;
    @Autowired
    private WebContext webContext;
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private QuestionDao questionDao;
    @Autowired
    private QuestionPvAnCountDao questionPvAnCountDao;

    /**
     * 验证权限
     *
     * @param questionId 问题ID
     * @return boolean
     * @author lyj
     * @since 2015-3-26
     */
    public boolean checkRole(final long questionId) {

        //判断登录用户是否为问题创建人
        if (questionDao.checkCreator(questionId) == 1) {
            log.debug("判断登录用户是否为问题创建人questionDao.checkCreator(questionId) == 1");
            return true;
        }

        if (webContext.getRole() != Roles.STUDENT) {

            //如果登录用户是超级管理员
            if (webContext.getRole() == Roles.SUPER_ADMIN) {
                log.debug("如果登录用户是超级管理员webContext.getRole() == Roles.SUPER_ADMIN");
                return true;
            }

            //判断问题所在课程群组是否为老师所管理的课程群组
            if (questionDao.checkGroup(questionId) == 1) {
                log.debug("判断问题所在课程群组是否为老师所管理的课程群组questionDao.checkGroup(questionId) == 1");
                return true;
            }
        }

        log.debug("验证权限");
        return false;

    }


    /**
     * 新增问题答案
     *
     * @param answer 答案实体
     * @return void
     * @author lyj
     * @since 2015-3-20
     */
    public void addAnswer(Answer answer){

        if (webContext.getRole() == Roles.COLLEGE_USER || webContext.getRole() == Roles.DEPT_ADMIN || webContext.getRole() == Roles.SPEC_LEADER) {
            throw new ServiceException("权限错误！");
        }

        //判断问题是否已解决，也判断问题是否已经被删除
        if (questionDao.checkStatus(answer.getQuestionId()) != 1){
            log.debug("新增问题答案questionDao.checkStatus(answer.getQuestionId()) != 1");
            log.warn("问题已解决，不能再回答！");
            throw new ServiceException("问题已解决，不能再回答！");
        }

        if (answerDao.addAnswer(answer) != 1){
            log.debug("新增问题答案answerDao.addAnswer(answer) != 1");
            log.warn("新增问题答案失败!");
            throw new ServiceException("新增问题答案失败!");
        }

        //递增问题回答数量
        questionPvAnCountDao.increment(answer.getQuestionId(), questionPvAnCountDao.ANSWER_COUNT, 1);
    }


    /**
     * 设置最佳答案
     *
     * @param answer 答案实体
     * @author lyj
     * @since 2015-3-20
     */
    @Transactional
    public void setBest(Answer answer){

        if (webContext.getRole() == Roles.COLLEGE_USER || webContext.getRole() == Roles.DEPT_ADMIN || webContext.getRole() == Roles.SPEC_LEADER) {
            throw new ServiceException("权限错误！");
        }

        //验证权限
        if (!checkRole(answer.getQuestionId())){
            log.debug("验证权限!checkRole(answer.getQuestionId())");
            log.warn("权限错误！");
            throw new ServiceException("权限错误！");
        }

        //判断答案是否已经被删除
        if (answerDao.getById(answer.getId(), 0, 0) != 1) {
            throw new ServiceException("答案已经被删除！");
        }

        //判断问题是否已解决
        Question question = questionDao.getDetail(answer.getQuestionId());
        if (question == null || question.getStatus() == QuestionCons.RESOLVED) {
            log.warn("获取问题明细失败或该问题已经解决！");
            throw new ServiceException("问题已解决或已删除！");
        }

        if (answerDao.setBest(answer) != 1){
            log.debug("设置最佳答案失败answerDao.setBest(answer) != 1");
            log.warn("设置最佳答案失败：id->{}!", answer.getId());
            throw new ServiceException("操作失败！");
        }


        //更改问题状态为已解决
        if (questionDao.setStatus(answer.getQuestionId(), QuestionCons.RESOLVED) != 1){
            log.debug("更改问题状态为已解决questionDao.setStatus(answer.getQuestionId(), QuestionCons.RESOLVED) != 1");
            log.warn("更改问题状态失败!");
            throw new ServiceException("操作失败！");
        }

    }


    /**
     * 删除答案权限判断
     * @param questionId
     * @param answerId
     * @return boolean
     * @author lyj
     * @since 2015-4-27
     */
    public boolean deleteCheck(final long questionId, final long answerId) {
        //判断登录用户是否为问题创建人
        if (questionDao.checkCreator(questionId) == 1) {
            log.debug("判断登录用户是否为问题创建人questionDao.checkCreator(questionId) == 1");
            return true;
        }

        if (webContext.getRole() != Roles.STUDENT) {

            //如果登录用户是超级管理员
            if (webContext.getRole() == Roles.SUPER_ADMIN) {
                log.debug("如果登录用户是超级管理员webContext.getRole() == Roles.SUPER_ADMIN");
                return true;
            }

            //判断问题所在课程群组是否为老师所管理的课程群组
            if (questionDao.checkGroup(questionId) == 1) {
                log.debug("判断问题所在课程群组是否为老师所管理的课程群组questionDao.checkGroup(questionId) == 1");
                return true;
            }
        } else {
            //判断是否为答案创建人，是否已经删除
            if (answerDao.getById(answerId, webContext.getUserId(), webContext.getRole()) == 1) {
                return true;
            }
        }

        return false;
    }


    /**
     * 删除答案
     *
     * @param id 答案ID
     * @return
     * @author lyj
     * @since 2015-3-20
     */
    public void deleteAnswer(final long id, final long questionId){

        if (webContext.getRole() == Roles.COLLEGE_USER || webContext.getRole() == Roles.DEPT_ADMIN || webContext.getRole() == Roles.SPEC_LEADER) {
            throw new ServiceException("权限错误！");
        }

        //验证权限
        if (!deleteCheck(questionId, id)){
            log.debug("删除答案!checkRole(questionId)");
            log.warn("权限错误！");
            throw new ServiceException("权限错误或答案已经删除！");
        }

        if (answerDao.deleteAnswer(id) != 1){
            log.debug("验证课程群组answerDao.deleteAnswer(id) != 1");
            log.warn("删除失败:id->{}!", id);
            throw new ServiceException("删除失败！");
        }
        //递减问题回答数量
        questionPvAnCountDao.increment(questionId, questionPvAnCountDao.ANSWER_COUNT, -1);
    }


    /**
     * 获取回答列表
     *
     * @param questionId 问题ID
     * @param pageNum 当前页码
     * @param pageSize 每页条数
     * @return
     * @author lyj
     * @since 2015-3-20
     */
    public Page<Answer> getList(final long questionId, final int pageNum, final int pageSize){
        if (webContext.getRole() == Roles.COLLEGE_USER || webContext.getRole() == Roles.DEPT_ADMIN || webContext.getRole() == Roles.SPEC_LEADER) {
            throw new ServiceException("权限错误！");
        }

        Page<Answer> page = answerDao.getList(questionId, pageNum, pageSize);

        //存储老师ID
        Set<Long> teacherIds = new HashSet<>();
        //存储学生ID
        Set<Long> studentIds = new HashSet<>();

        if (page.getItems().size() == 0){
            log.debug("如果集合为空page.getItems().size() == 0");
            return page;
        }

        //循环读取创建人ID
        log.debug("循环读取创建人ID");
        for (Answer answer : page.getItems()){
            if (answer.getRole() == 0){
                log.debug("answer.getRole() == 0");
                teacherIds.add(answer.getCreatorId());
            } else {
                log.debug("answer.getRole() != 0");
                studentIds.add(answer.getCreatorId());
            }
        }

        //获取教师头像、姓名
        Map<Long, Teacher> reTeacher = teacherService.getPictures(teacherIds);
        //获取学生头像、姓名
        Map<Long, Student> reStudent = studentService.getPictures(studentIds);

        //循环绑定头像和姓名
        log.debug("循环绑定头像和姓名");
        for (Answer answer : page.getItems()){
            if (answer.getRole() == 0) {
                log.debug("answer.getRole() == 0");
                answer.setCreatorName(reTeacher.get(answer.getCreatorId()).getName());
                answer.setCreatorPhoto(reTeacher.get(answer.getCreatorId()).getPicture());
            } else {
                log.debug("answer.getRole() != 0");
                answer.setCreatorName(reStudent.get(answer.getCreatorId()).getName());
                answer.setCreatorPhoto(reStudent.get(answer.getCreatorId()).getAvatar());
            }
        }

        log.debug("获取回答列表");
        return page;
    }
}
